#include "quene.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->front = NULL;
	q->rear = NULL;
}

void QueuePrint(Queue* q)
{
	assert(q);
	QNode* cur = q->front;
	printf("head-");
	while (cur)
	{
		printf("%d-", cur->data);
		cur = cur->pNext;
	}
	printf("tail\n");
}

void QueuePush(Queue* q, QDataType dat)
{
	QNode* new = (QNode*)malloc(sizeof(QNode));
	if (new == NULL)
	{
		exit(-1);
	}
	new->data = dat;
	new->pNext = NULL;
	if (q->front == NULL)
	{
		q->front = new;
		q->rear = new;
	}
	else
	{
		q->rear->pNext = new;
		q->rear = q->rear->pNext;
	}
	
}


void QueuePop(Queue* q)
{
	assert(q);
	if (q->front == NULL)
	{
		return;
	}
	if (q->front)
	{
		QNode* cur = q->front;
		q->front = q->front->pNext;
		if (q->front == NULL)
		{
			q->rear = NULL;
		}
		free(cur);
		cur = NULL;
	}
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	if (q->front == NULL)
	{
		exit(-1);
	}
	else
	{
		return q->front->data;
	}
	
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	if (q->rear == NULL)
	{
		exit(-1);
	}
	else
	{
		return q->rear->data;
	}
}


int QueueSize(Queue* q)
{
	assert(q);
	int size = 0;
	if ((q->front == q->rear) && (q->front == NULL))
	{
		return size;
	}
	QNode* cur = q->front;
	while (cur != q->rear)
	{
		size++;
		cur = cur->pNext;
	}
	size++;
	return size;
}

bool QueueEmpty(Queue* q)
{
	assert(q);
	if ((q->front == q->rear) && (q->front == NULL))
	{
		return true;
	}
	else
	{
		return false;
	}
}

void QueueDestroy(Queue* q)
{
	assert(q);
	while (q->front != q->rear)
	{
		QNode* cur = q->front;
		q->front = q->front->pNext;
		free(cur);
		cur = NULL;
	}
	free(q->front);
	q->front = NULL;
	q->rear = NULL;
}
